package com.ruoyi.binance.api;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;

public class SignatureUtils {
    public static String getSignature(HashMap<String, Object> paramMap) {
        byte[] hmacSha256;
        try {
            StringBuilder data = new StringBuilder();
            for (String key : paramMap.keySet()){
                data.append(key).append("=").append(paramMap.get(key)).append("&");
            }
            //去掉最后一个&符号
            data.deleteCharAt(data.length() - 1);
            SecretKeySpec secretKeySpec = new SecretKeySpec(Config.API_SECRET.getBytes(), Config.HMAC_SHA256);
            Mac mac = Mac.getInstance(Config.HMAC_SHA256);
            mac.init(secretKeySpec);
            hmacSha256 = mac.doFinal(data.toString().getBytes());
        } catch (Exception e) {
            throw new RuntimeException("Failed to calculate hmac-sha256", e);
        }
        return Hex.encodeHexString(hmacSha256);
    }
}
